<?php

namespace base;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
use yii\data\Pagination;
use common\models\Board;


/**
 * Site controller
 */
class BaseController extends Controller
{
	public $defaultRoute = 'index';
	

	private $_cachedRoles;
	
	public $requests;
	
	public $root_dir;
	
	public function init(){
	    parent::init();
		$this->root_dir = dirname(Yii::getAlias('@web'));	
		
	}
	
	public function createUrl($route){
		return Yii::$app->urlManager->createUrl($route);
	}

	public function postSave($model)
	{
		return $model->load(Yii::$app->request->post()) && $model->save();
	}
	
	
	
	public function echojson($data = array(), $array = []){
		header('Content-Type:application/json; charset=utf-8');
		$data = array_merge(array('msg'=>'ok', 'code'=>200, 'counts'=>0), $data);
		if (!isset($data['results'])) $data['results'] = array();
		$data = json_encode($data, JSON_UNESCAPED_UNICODE);
		echo isset($this->requests['jsonpcallback']) ? $this->requests['jsonpcallback']."(" . $data . ")" : $data;
		unset($data);
		exit();

	}

	/**
	 * 输出JSON格式的错误信息
	 * @param $errormsg 错误提示
	 * @param $errcode  错误代码
	 */
	public function errmsg($errormsg = '参数可能不对', $errcode = 500){
		self::echojson(array('msg'=>$errormsg, 'code'=>$errcode));
	}

	/**
	 * 检查必传参数
	 * @param $data json参数数组
	 * @param $param  要检查的必填参数数组
	 * return 错误提示json
	 */
	public function isRequired($param, $checktoken = false){
		$data = $this->requests;
		//echo json_encode($data);
		//exit;
		$array = array();
		//这里判断uid是否丢失或为空
		if (in_array('uid', $param)){
			if (!isset($data['uid']) || empty($data['uid'])) $this->errmsg('uid呢？',400);
		}

		//if ($checktoken) self::CheckToken();
		foreach($param as $k=>$v){
			if (!isset($data[$v])){
				self::errmsg('缺少参数：'.$v);
			}else{
				if(!is_numeric($data[$v]) && empty($data[$v])){
					self::errmsg('缺少参数：'.$v);
				}
			}
			$array[':'.$v] = $data[$v];
		}
		return $array;
	}


	/**
	 * 数组分页查询
	 * @param $sql sql语句
	 * @param $orderby 排序
	 * @return array
	 */
	public function arrayPages($array = array(), $echojson = true){
		$json = $this->requests;
		$page = isset($json['pageno']) ? intval($json['pageno']) : 1;
		$pagesize = isset($json['pagesize']) ? intval($json['pagesize']) : 10;
		$_GET['pageno'] = (int)($page<1 ? 1 : $page);
		$rows['counts'] = count($array);
		$rows['pagecount'] = (int)ceil($rows['counts'] / $pagesize);
		if ($_GET['pageno'] > $rows['pagecount'] || $rows['counts'] == 0){
			$rows['pageno'] = $_GET['pageno'];
			$rows['results'] = array();
		}else{
			$rows['pageno'] = $_GET['pageno'] > $rows['pagecount'] && $rows['pagecount']>0 ? $rows['pagecount'] : $_GET['pageno'];
			$rows['results'] = array_slice($array, ($rows['pageno']-1)*$pagesize, $pagesize);
		}
		if($echojson){
			self::echojson($rows);
		}else{
			return $rows;
		}
	}
	/**
	 * SQL分页查询
	 * @param $sql sql语句
	 * @param $orderby 排序
	 * @return array
	 */
	public function queryPages($sql, $bindparam = array(), $orderby = '', $echojson = true){
		$json = $this->requests;
		$page = isset($json['pageno']) ? intval($json['pageno']) : 1;
		$pagesize = isset($json['pagesize']) ? intval($json['pagesize']) : 10;
		$_GET['pageno'] = (int)($page<1 ? 1 : $page);
		$sqlcount = preg_replace("/^SELECT(.*)FROM/i", "SELECT count(*) FROM", $sql);
		$db = \Yii::$app->db;
		$conn = $db->createCommand($sqlcount);
		$conn->bindValues($bindparam);
		$rows['counts'] = (int)$conn->queryScalar();
		$rows['pagecount'] = (int)ceil($rows['counts']/$pagesize);
		if ($_GET['pageno'] > $rows['pagecount'] || $rows['counts'] == 0){
			$rows['pageno'] = $_GET['pageno'];
			$rows['results'] = array();
		}else{
			$rows['pageno'] = $_GET['pageno'] > $rows['pagecount'] && $rows['pagecount']>0 ? $rows['pagecount'] : $_GET['pageno'];
			$conn = $db->createCommand($sql.' '.$orderby." LIMIT :offset,:limit");
			$conn->bindValues($bindparam);
			$conn->bindValue(':offset', ($rows['pageno']-1)*$pagesize);
			$conn->bindValue(':limit', $pagesize);
			$rows['results'] = $conn->queryAll();
		}
		if (!\Yii::$app->user->isGuest) $rows['sql'] = $conn->getSql();
		if($echojson){
			self::echojson($rows);
		}else{
			return $rows;
		}
	}



	/* @param $sql sql语句
	 *  @bindparam 绑定的字段和值
	 *  @echojson 是否直接输出json
	 *  @return array
	 */
	public function queryAll($sql, $bindparam = array(), $echojson = true){
		$conn = \Yii::$app->db->createCommand($sql);
		$conn->bindValues($bindparam);
		try{
			$data = $conn->queryAll();
			$rows['counts'] = count($data);
			$rows['results'] = $data;
			//if (!\Yii::$app->user->isGuest) $rows['sql'] = $conn->text;
		}catch (Exception $e){
			self::errmsg('db error '.$e->getMessage());
		}
		if($echojson){
			self::echojson($rows);
		}else{
			return $rows;
		}
	}

    

	/* @param $sql sql语句
	 *  @bindparam 绑定的字段和值
	 *  @echojson 是否直接输出json
	 *  @return array
	 */
	public function query($sql, $bindparam = array(), $type = '', $echojson = true){
		$conn = \Yii::$app->db->createCommand($sql);
		$conn->bindValues($bindparam);
		try{
			switch($type){
				case 'execute':
					$data = $conn->execute();
					break;
				case 'one':
					$data = $conn->queryOne();
					break;
				case 'column':
					$data = $conn->queryColumn();
					break;
				case 'all':
					$data = $conn->queryAll();
					break;
				case 'scalar':
					$data = $conn->queryScalar();
					break;
				default:
					$data = $conn->query();
			}

			//$rows['counts'] = count($data);
			$rows = $data;
			//if (!\Yii::$app->user->isGuest) $rows['sql'] = $conn->text;
		}catch (Exception $e){
			self::errmsg('db error '.$e->getMessage());
		}
		if($echojson){
			self::echojson($rows);
		}else{
			return $rows;
		}
	}


	/* @param $sql sql语句
	 *  @bindparam 绑定的字段和值
	 *  @echojson 是否直接输出json
	 *  @return array
	 */
	public function queryResult($sql, $bindparam = array(), $echojson = true){
		$conn = \Yii::$app->db->createCommand($sql);
		$conn->bindValues($bindparam);
		try{
			$conn->execute();
			$rows['state'] = 1;
		}catch (Exception $e){
			$rows['state'] = 0;
			$rows['error'] = $e->getMessage();
		}
		//if (!\Yii::$app->user->isGuest) $rows['sql'] = $conn->text;
		if($echojson){
			self::echojson($rows);
		}else{
			return $rows;
		}
	}

	public function curlJson($url, $postdata, $get_as_json=true,$memcard=''){
		$data_string = json_encode($postdata);
		$SALT = 'cn-healthcare_';
		$sid = microtime();

		$headerArr = array(
		    'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string),
			'package: sssss',
			'sid: '.$sid,
			'ssid: '.md5($SALT.$sid),
			'memcard: '.$memcard
		);


		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headerArr);
		$output = curl_exec($ch);
		if (curl_errno($ch)) {
			exit(curl_error($ch));
		} else {
			$output = $get_as_json?$output:json_decode($output, true);
		}
		return $output;

	}

	public function curlGet($url, $data = array(), $return_array = true, $method = 'GET'){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$output = curl_exec($ch);
		if ($output === false){
			echo 'Curl error: ' . curl_error($ch);
		}else{
			return $return_array ? json_decode($output,true) : $output;
		}
	}

}
